package com.github.pudding.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Stephen
 * @since 2018/8/31
 */
public class CharsetFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpReq = (HttpServletRequest) request;
        httpReq.setCharacterEncoding(encoding);

        HttpServletResponse httpResp = (HttpServletResponse) response;
        httpResp.setCharacterEncoding(encoding);

        //调用下一个filter
        chain.doFilter(httpReq, httpResp);
    }

    @Override
    public void destroy() {

    }
}
